<?php
namespace app\index\controller;

use app\common\controller\CommonBase;
use app\common\model\User as UserModel;
use think\facade\Cache;
use think\facade\Log;
use wechat\Wechat as WechatApi;
use wechat\WechatAuth;

class Wechat extends CommonBase
{

    private $openId;
    private $msgType;
    private $wechat;
    private $wxRequest = array();

    protected function initialize()
    {
        parent::initialize();

        $wechat = new WechatApi($this->siteConfig['weixin_token'],$this->siteConfig['weixin_appid'],$this->siteConfig['weixin_aes_key']);
        Log::info(json_encode($wechat->request()));

        $request = $wechat->request();
        $this->wxRequest = $wechat->request();

        $this->msgType = $request['MsgType'];
        $this->openId = $request['FromUserName'];

        $this->wechat = $wechat;
    }

    public function index()
    {
        switch ($this->msgType)
        {
            case WechatApi::MSG_TYPE_TEXT:
                $this->replyText();
                break;
            case WechatApi::MSG_TYPE_EVENT:
                $this->replyEvent();
                break;
        }

    }

    private function replyText()
    {
        $this->wechat->replyText("hello " . $this->openId);
    }

    private function replyEvent()
    {
        if ($this->wxRequest["Event"] == WechatApi::MSG_EVENT_SCAN ||
            ($this->wxRequest["Event"] == WechatApi::MSG_EVENT_SUBSCRIBE && strpos($this->wxRequest['EventKey'],"qrscene_") == 0)
        )
        {

            $wechat = new WechatAuth($this->siteConfig['weixin_appid'],$this->siteConfig['weixin_secret']);
            $user_info = $wechat->userInfo($this->openId);

            if (!UserModel::checkUserIsExist("weixin","",$this->openId)) {
                UserModel::createUser("",$user_info['headimgurl'],$user_info['nickname'],md5(rand(1000,10000) . time()),$user_info['sex'],"weixin",$user_info['openid']);
            }

            $user = UserModel::userLogin("weixin","",$user_info['openid']);

            $key = str_replace("qrscene_","",$this->wxRequest['EventKey']);
            Cache::set('weixin_qr_login_id_' . $key,$user['id']);

            $this->wechat->replyText("恭喜站点登录成功!");
        }

    }
}
